from flask_sqlalchemy import SQLAlchemy
from flask import abort
import traceback
from ..libs.unit import abort_msg
from contextlib import contextmanager

# 实例化数据库对象
db = SQLAlchemy()

# 序列化
def serialize(model):
    from sqlalchemy.orm import class_mapper
    columns = [c.key for c in class_mapper(model.__class__).columns]
    return dict((c, getattr(model, c)) for c in columns)

# 自动提交 or 回滚，上下文管理
@contextmanager
def auto_commit():
    try:
        yield
        db.session.commit()
    except Exception as e:
        print('### 数据库查询异常 ###')
        print("traceback:", traceback.format_exc())
        db.session.rollback()
        abort(500, abort_msg(e))
